﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Yelper.Phone;
using System.ComponentModel;
using System.Windows.Navigation;

namespace Yelper_Phone {
    public partial class Login : PhoneApplicationPage {
        public Login() {
            InitializeComponent();            
        }

        protected override void OnNavigatedTo(NavigationEventArgs e) {
            YelperStatic.App.CheckCredentialsCompleted += new EventHandler<AsyncCompletedEventArgs>(YelperAPI_CheckCredentialsCompleted);
            base.OnNavigatedTo(e);
        }

        private void Button_Click(object sender, RoutedEventArgs e) {
            ButtonLogin.IsEnabled = false;            
            ProgressBar.IsIndeterminate = true;

            YelperStatic.App.CheckCredentialsAsync(TextBoxUsername.Text, PasswordBox.Password);
        }

        private void YelperAPI_CheckCredentialsCompleted(object sender, AsyncCompletedEventArgs e) {
            Dispatcher.BeginInvoke(() => {                
                ProgressBar.IsIndeterminate = false;
            });

            if (e.Error != null) {
                Dispatcher.BeginInvoke(() => { ButtonLogin.IsEnabled = true; });
                //TODO: toon foutbox!
            } else {                
                Dispatcher.BeginInvoke(() => {
                    if (CheckBoxRememberMe.IsChecked.GetValueOrDefault(false)) {
                        YelperStatic.App.SaveCredentials();
                    }
                    YelperStatic.App.CheckCredentialsCompleted -= new EventHandler<AsyncCompletedEventArgs>(YelperAPI_CheckCredentialsCompleted);
                    NavigationService.GoBack();
                });                
            }
        }
    }
}
